<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数: {{ total }} 条</span>
        </template>

        <template #right>
          <!-- v-if="hasPointsPermission('excel_import')" -->
          <el-button
            v-permission="'excel_import'"
            type="warning"
            size="small"
            @click.native="$router.push('/import?type=user')"
            >excel导入</el-button
          >
          <!-- v-if="hasPointsPermission('excel_export')" -->
          <el-button
            v-permission="'excel_export'"
            type="danger"
            size="small"
            @click.native="exportExcel"
            >excel导出</el-button
          >
          <!-- v-if="hasPointsPermission('p-em-add')" -->
          <el-button
            v-permission="'p-em-add'"
            type="primary"
            size="small"
            @click.native="addemployeefn"
            >新增员工</el-button
          >
        </template>
      </page-tools>

      <el-card v-loading="showLoading" style="margin-top: 10px">
        <el-table border :data="EmployeesList">
          <el-table-column label="序号" type="index" :index="indexMethod" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="头像">
            <template #default="{ row }">
              <img
                v-Imgerror="defaultImg"
                :src="row.staffPhoto || nullImg"
                class="staff"
              />
            </template>
          </el-table-column>
          <el-table-column label="手机号" prop="mobile" />
          <el-table-column label="工号" prop="workNumber" />
          <el-table-column
            label="聘用形式"
            prop="formOfEmployment"
            :formatter="formatter"
          />
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry">
            <template #default="{ row }">
              {{ formartTime(row.timeOfEntry) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" fixed="right" width="280">
            <template #default="{ row }">
              <!-- v-if="hasPointsPermission('p-em-look')" -->
              <el-button
                v-permission="'p-em-look'"
                type="text"
                size="small"
                @click.native="$router.push(`/employees/detail/${row.id}`)"
                >查看</el-button
              >
              <!-- v-if="hasPointsPermission('assign_role')" -->
              <el-button
                v-permission="'assign_role'"
                type="text"
                size="small"
                @click="editRole(row.id)"
                >分配角色</el-button
              >
              <!-- v-if="hasPointsPermission('p-em-del')" -->
              <el-button
                v-permission="'p-em-del'"
                type="text"
                size="small"
                @click.native="delEmployeesList(row.id)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <div style="height: 60px; margin-top: 10px">
          <el-pagination
            :current-page="page"
            :page-size="size"
            :page-sizes="[10, 20, 30, 40]"
            :total="total"
            layout="total,sizes,prev, pager, next,jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
      <add-employee :show-dialog.sync="showDialog" />
      <assign-role :show-role-dialog.sync="showRoleDialog" :user-id="userId" />
    </div>
  </div>
</template>

<script>
import { getEmployeeListAPI, delEmployeesListAPI } from '@/api/employees'
import EmployeesType from '@/constant/employees'
import dayjs from 'dayjs'
import addEmployee from './componets/add-employee.vue'
import avatar from '@/assets/common/bigUserHeader.png'
import assignRole from './componets/assign-role.vue'
import { mapGetters } from 'vuex'
// 使用mixins的方式  1.先导入mixins所在的文件 2.把mixins混入当前组件中(mixins: [permission])
import permission from '@/mixins/permission'
export default {
  name: 'Employees',
  components: {
    addEmployee,
    assignRole
  },
  mixins: [permission],
  data() {
    return {
      EmployeesList: [], // 保存接口返回的数据
      page: 1,
      size: 10,
      total: 0,
      showLoading: false, // 控制加载效果
      showDialog: false,
      defaultImg: avatar, // 默认图
      // 如果头像是null的话我们展示nullImg
      nullImg:
        'https://img0.baidu.com/it/u=4038088789,1477271819&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500',
      showRoleDialog: false, // 控制分配角色的弹框
      userId: ''
    }
  },
  computed: {
    ...mapGetters(['roles'])
  },
  created() {
    // console.log(this.roles)
    // 调用获取员工列表方法
    this.getEmployeeList()
  },
  methods: {
    // 封装按钮权限方法   这个后来封装到了mixins
    // hasPointsPermission(point) {
    //   return this.roles?.points.includes(point)
    // },
    // 分配角色打开弹框
    editRole(id) {
      this.showRoleDialog = true
      this.userId = id
    },
    async getEmployeeList() {
      // 调用获取员工列表数据接口
      this.showLoading = true
      const { data } = await getEmployeeListAPI(this.page, this.size)
      this.EmployeesList = data.rows
      this.total = data.total
      this.showLoading = false
    },
    indexMethod(index) {
      // 这个参数index是从0开始的
      return (this.page - 1) * this.size + index + 1
    },
    handleSizeChange(val) {
      this.size = val
      this.getEmployeeList()
    },
    handleCurrentChange(val) {
      this.page = val
      this.getEmployeeList()
    },
    // 格式化form表单里的单项内容
    formatter(row, column, cellValue, index) {
      // console.log(row, column, cellValue, index)
      const hireObj = EmployeesType.hireType.find(
        (item) => item.id === +cellValue
      )
      return hireObj ? hireObj.value : '未知形式'
    },
    // 格式化时间的方法
    formartTime(time) {
      return dayjs(time).format('YYYY-MM-DD')
    },
    // 封装删除方法
    delEmployeesList(id) {
      this.$confirm('你确定要删除吗', '温馨提示')
        .then(async() => {
          await delEmployeesListAPI(id) // 调接口
          this.$message.success('删除成功') // 提示
          if (this.page > 1 && this.EmployeesList.length === 1) {
            this.page--
          }
          this.getEmployeeList() // 重新获取数据渲染页面
        })
        .catch(() => {
          // 取消什么都不做但是catch 也要写
        })
    },
    // 封装添加员工的方法
    addemployeefn() {
      this.showDialog = true
    },
    // excel导出方法
    async exportExcel() {
      // 获取所有的员工数据
      const {
        data: { rows }
      } = await getEmployeeListAPI(1, this.total)
      // console.log(rows)
      const headersRelations = {
        姓名: 'username',
        手机号: 'mobile',
        入职日期: 'timeOfEntry',
        聘用形式: 'formOfEmployment',
        转正日期: 'correctionTime',
        工号: 'workNumber',
        部门: 'departmentName'
      }
      const multiHeader = [['姓名', '主要信息', '', '', '', '', '部门']]
      const merges = ['A1:A2', 'B1:F1', 'G1:G2']
      const headersArr = [
        '姓名',
        '手机号',
        '入职日期',
        '聘用形式',
        '转正日期',
        '工号',
        '部门'
      ]
      const data = this.formateData2Array(headersRelations, rows, headersArr)
      import('@/vendor/Export2Excel').then((excel) => {
        excel.export_json_to_excel({
          header: headersArr, // 表头 必填
          // 导出的数据必须是二维数组
          data: data,
          filename: '员工信息', // 导出文件的文件名
          autoWidth: true, // 单元格宽度是否自适应
          bookType: 'xlsx', // 文件的后缀名
          multiHeader, // 合并表头所需
          merges // 合并表头所需
        })
      })
    },
    formateData2Array(headersRelations, rows, headersArr) {
      const arr = []
      rows.forEach((item) => {
        const tempArray = []
        headersArr.forEach((key) => {
          const Engkey = headersRelations[key]
          let value = item[Engkey]
          if (Engkey === 'formOfEmployment') {
            const hireObj = EmployeesType.hireType.find(
              (item) => item.id === +value
            )
            value = hireObj ? hireObj.value : '未知形式'
          }
          if (['timeOfEntry', 'correctionTime'].includes(Engkey)) {
            value = this.formartTime(value)
          }
          tempArray.push(value)
        })
        arr.push(tempArray)
      })
      return arr
    }
  }
}
</script>

<style lang="scss" scoped>
.employees-container {
  .staff {
    width: 70px;
    height: 70px;
    border-radius: 50%;
  }
}
</style>
